package com.tinyideatech.common.utils;

import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StrUtil {

    public static Long[] toLongArray(String split, String str) {
        if (StringUtils.isEmpty(str)) {
            return new Long[] {};
        }
        String[] arr = str.split(split);
        final Long[] ints = new Long[arr.length];
        for (int i = 0; i < arr.length; i++) {
            final Long v = toLong(arr[i], 0L);
            ints[i] = v;
        }
        return ints;
    }

    public static Long toLong(Object value, Long defaultValue) {
        if (value == null) {
            return defaultValue;
        }
        if (value instanceof Long) {
            return (Long) value;
        }
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        final String valueStr = toStr(value, null);
        if (StringUtils.isEmpty(valueStr)) {
            return defaultValue;
        }
        try {
            // 支持科学计数法
            return new BigDecimal(valueStr.trim()).longValue();
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static String toStr(Object value, String defaultValue) {
        if (null == value) {
            return defaultValue;
        }
        if (value instanceof String) {
            return (String) value;
        }
        return value.toString();
    }

    public static List<String> getList(String str) {
        List<String> list = Arrays.asList(str.split(","));
        return new ArrayList(list);
    }

    public static String getLastId(String id){
        if(id.length() > 7){
            Pattern p = Pattern.compile("[0-9]+[X|x]{1}");
            Matcher m = p.matcher(id);
            boolean b = m.matches();
            if(b){
                id=id.substring(id.length()-7,id.length()-1);
            }else{
                id=id.substring(id.length()-6);
            }
        }
        return id;
    }

    public static String getEncodeURL(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}
